<template>
  <el-dialog
    v-model="visible"
    title="新增法院"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="法院名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入法院名称" maxlength="100" />
      </el-form-item>

      <el-form-item label="法院级别" prop="level">
        <el-select v-model="form.level" placeholder="请选择法院级别" style="width: 100%">
          <el-option label="中华人民共和国最高人民法院" value="1" />
          <el-option label="高级人民法院" value="2" />
          <el-option label="中级人民法院" value="3" />
          <el-option label="基层人民法院" value="4" />
          <el-option label="专门人民法院" value="5" />
          <el-option label="人民法庭" value="6" />
          <el-option label="其他司法机构" value="7" />
        </el-select>
      </el-form-item>

      <el-form-item label="所在地区" prop="province">
        <RegionCascader
          v-model="regionData"
          emit-path
          placeholder="请选择省/市/区"
          @change="handleRegionChange"
        />
      </el-form-item>

      <el-form-item label="详细地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入详细地址" maxlength="200" />
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="50" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import request from '@/utils/request'
  import { RegionCascader } from '@/components/business/region'
  import type { ApiResponse } from '@/types/api'

  interface CourtForm {
    name: string
    level: string
    province: string
    city: string
    district: string
    address: string
    phone: string
  }

  interface Court {
    id: number
    name: string
    province: string
    city: string
    district: string
    address: string
    phone: string
    level: string
  }

  const props = defineProps<{
    modelValue: boolean
    initialName?: string
  }>()

  const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void
    (e: 'success', court: Court): void
  }>()

  const visible = ref(false)
  const loading = ref(false)
  const formRef = ref()
  const regionData = ref<string>('')

  // 处理地区选择变化
  const handleRegionChange = (value: string | string[] | null, selectedOptions: any[]) => {
    console.log('地区选择变化:', value, selectedOptions)
    if (value && selectedOptions && selectedOptions.length > 0) {
      // 从selectedOptions中获取完整的省市区信息
      const province = selectedOptions[0]
      const city = selectedOptions.length > 1 ? selectedOptions[1] : null
      const district = selectedOptions.length > 2 ? selectedOptions[2] : null

      // 使用id字段而不是code字段，并确保转换为字符串
      form.province = province?.id ? String(province.id) : ''
      form.city = city?.id ? String(city.id) : ''
      form.district = district?.id ? String(district.id) : ''
    } else if (value) {
      // 如果没有selectedOptions，尝试从value中解析
      if (Array.isArray(value)) {
        // 如果value是数组，取最后一个值作为区县代码
        form.district = value.length > 0 ? String(value[value.length - 1]) : ''
        // 如果数组长度大于1，设置市
        if (value.length > 1) {
          form.city = String(value[value.length - 2]) || ''
        }
        // 如果数组长度大于2，设置省
        if (value.length > 2) {
          form.province = String(value[0]) || ''
        }
      } else if (typeof value === 'string' && value.includes('/')) {
        // 如果value是完整路径字符串，解析它
        const codes = value.split('/')
        form.province = codes[0] || ''
        form.city = codes[1] || ''
        form.district = codes[2] || ''
      } else {
        // 否则使用value作为区县代码
        form.district = String(value) || ''
      }
    } else {
      form.province = ''
      form.city = ''
      form.district = ''
    }
    console.log('更新后的表单数据:', {
      province: form.province,
      city: form.city,
      district: form.district,
    })
  }

  const form = reactive<CourtForm>({
    name: '',
    level: '4', // 默认基层法院
    province: '',
    city: '',
    district: '',
    address: '',
    phone: '',
  })

  const rules = {
    name: [
      { required: true, message: '请输入法院名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    ],
    // 修改验证规则，检查province字段而不是district字段
    province: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
  }

  const handleClose = () => {
    visible.value = false
    emit('update:modelValue', false)
    resetForm()
  }

  // 定义地区数据类型

  // 监听地区数据变化
  watch(
    () => [form.province, form.city, form.district],
    ([province, city, district]) => {
      // 如果有完整的省市区数据，则更新regionData
      if (province && city && district) {
        // RegionCascader组件需要完整的路径字符串，格式为 "省份代码/城市代码/区县代码"
        regionData.value = `${province}/${city}/${district}`
      } else if (province && city) {
        regionData.value = `${province}/${city}`
      } else if (province) {
        regionData.value = province
      } else {
        regionData.value = ''
      }
    },
    { immediate: true }
  )

  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.assign(form, {
      name: '',
      level: '4',
      province: '',
      city: '',
      district: '',
      address: '',
      phone: '',
    })
    regionData.value = ''
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      loading.value = true

      // 在提交前检查地区数据
      console.log('提交前的表单数据:', form)
      if (!form.province || !form.city || !form.district) {
        ElMessage.error('请选择完整的地区信息')
        loading.value = false
        return
      }

      const requestData = {
        court_name: form.name,
        level: form.level,
        province: form.province,
        city: form.city,
        district: form.district,
        address: form.address,
        phone: form.phone,
      }

      console.log('发送请求数据:', requestData)

      // 注意：axios响应拦截器已经处理了response，直接返回了响应数据部分
      const response = await request.post<ApiResponse<{ id: number }>>(
        '/api/lawcase/courts/add',
        requestData
      )

      console.log('后端响应:', response)
      console.log('响应类型:', typeof response)
      console.log('响应code:', response.code)
      console.log('响应data:', response.data)

      // 检查响应状态码
      if (response.code === 0) {
        console.log('进入成功分支')
        // 构造完整的Court对象，使用后端返回的id和前端表单数据
        const courtData: Court = {
          id: (response.data as unknown as { id: number })?.id || 0, // 从响应数据中获取ID
          name: form.name,
          level: form.level,
          province: form.province,
          city: form.city,
          district: form.district,
          address: form.address,
          phone: form.phone,
        }
        console.log('构造的courtData:', courtData)
        ElMessage.success('法院添加成功')
        emit('success', courtData)
        handleClose()
      } else {
        console.log('进入失败分支')
        ElMessage.error(response.msg || '添加失败')
      }
    } catch (error: any) {
      console.error('添加法院失败:', error)
      ElMessage.error(error.message || '添加失败，请重试')
    } finally {
      loading.value = false
    }
  }

  // 统一监听modelValue变化
  watch(
    () => props.modelValue,
    newVal => {
      visible.value = newVal
      if (newVal) {
        // 重置表单并预填名称
        form.name = props.initialName || ''
        form.level = '4' // 默认基层法院
        form.province = ''
        form.city = ''
        form.district = ''
        form.address = ''
        form.phone = ''
        regionData.value = ''
      }
    }
  )
</script>

<style scoped>
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
</style>
